<?php
session_start();
if (!isset($_SESSION['rol'])) {
  header('Location:index.php');
  die();
}

if (isset($_POST['palabra_dibujada'])) {
  $_SESSION['palabra_dibujada'] = $_POST['palabra_dibujada']; 
}


?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Hackathon Paraguay</title>

        <!-- jQuery -->
        <script type="text/javascript" src="js/jquery/jquery.1.8.2.min.js"></script>
        <script type="text/javascript" src="js/jquery/jquery.ui.core.min.js"></script>
        <script type="text/javascript" src="js/jquery/jquery.ui.widget.min.js"></script>
        <script type="text/javascript" src="js/jquery/jquery.ui.mouse.min.js"></script>
        <script type="text/javascript" src="js/jquery/jquery.ui.draggable.min.js"></script>

        <!-- wColorPicker -->
        <link rel="stylesheet" type="text/css" href="css/wColorPicker.css" />
        <script type="text/javascript" src="js/wpaint/wColorPicker.js"></script>

        <!-- wPaint -->
        <link rel="stylesheet" type="text/css" href="css/wPaint.css" />
        <script type="text/javascript" src="js/wpaint/wPaint.js"></script>

        <!-- bootstrap -->
        <link rel="stylesheet" href="css/bootstrap.css">
        <link rel="stylesheet" href="css/bootstrap-responsive.min.css">
	<link href='http://fonts.googleapis.com/css?family=Mouse+Memoirs' rel='stylesheet' type='text/css'>

        <script type="text/javascript" src="js/bootstrap/bootstrap.js"></script>
        <script type="text/javascript" src="js/bing.js"></script>

        <style type="text/css">
            #resultados, #wPaint {
              margin:0 auto;
            }
            
            .drawbox {
              margin:0 auto; width:640px;
            }
            
            .typeText{
	      color:green; text-align:center;
	    }
	    
	    .typeHeader {
   	      text-align:center;
 	      font: 5em 'Mouse Memoirs'; 
	    }
	    
            #avisoSiNoEncuentra {
              color: #f00; margin: 7px;
            }
        </style>
    </head>
    <body>
        <div class="container-fluid">
            <div class="row-fluid">
                <div class="span10">
                    <h2 class="typeHeader">Just Draw</h2>
                    <h2 class="typeText">Bienvenido <?php echo strtoupper($_SESSION['nickname']);?>. <?php
                     if ($_SESSION['rol'] == 'dibujante') {
                       echo 'Ingrese la palabra y dibuje!';
                     } else {
                     	echo 'Adivine de qu&eacute; trata el dibujo';   
                     }
                    ?></h2>
                    <br/>
                    <div class="drawbox">	
                    <?php if($_SESSION['rol'] == 'adivinador'):?>
                        <form class="form-guess" method="POST">
                            <input type="text" Placeholder="Adivinar palabra" id="palabra_supuesta" name="palabra_supuesta" class="input-medium search-query">
                            <button type="button" class="btn" onclick="APP.tryEndGame(); return false;">Ok</button><br />
                            <p id="avisoSiNoEncuentra"></p>
                        </form>
                        
                        <div id="tapa" style="display:inline-block; position:absolute; background-color: red; z-index:99; width:645px; height:485px; opacity:0;"></div>
                        
                    <?php else: ;?>
                        
                        <form class="form-search">
                            <input type="text" Placeholder="Palabra a dibujar" id="palabra_dibujada"  name="palabra_dibujada" class="input-medium search-query">
                            <button type="submit" class="btn" >Ok</button>
                        </form>
                        
                    <?php endif;?>
                    </div>    
                    <div id="wPaint" style="display:inline; position:absolute; width:640px; height:480px; background:#CACACA; border:solid black 1px; overflow:hidden;"></div>

                </div>
                <div class="span2">
                    <div id="resultados"></div>
                </div>
            </div>

	<script type="text/javascript">
	        var APP = {};
	        
	        APP.tryEndGame = function() {
	          var palabra_supuesta = jQuery('#palabra_supuesta').val();
	          jQuery.post('verifica_palabra.php', {palabra_supuesta : palabra_supuesta}, function(data) {
                    if (data.ok) {
                      jQuery('#avisoSiNoEncuentra').text('');
                      alert('ACERTASTE!!! Este es el fin del juego.');
                      dispatchCommand('tryEndGame', {palabra_supuesta: palabra_supuesta});
                      window.location.replace('limpia.php');
                    } else {
                      jQuery('#avisoSiNoEncuentra').text('Palabra incorrecta! Vuelva a intentar');
                    }
	          });
	        };
		
		var processDispatch = function(command, params) {
		  if (command == 'pencilUp') {
		    wp.drawPencilUp(null, wp);
		  } else if (command == 'move') {
	            wp.drawPencilMove(params, wp);
		  } else if (command == 'pencilDown') {
		    wp.drawPencilDown(params, wp);
		  } else if (command == 'settings') {
		    for (var k in params) {
		      if (params.hasOwnProperty(k)) {
		        APP.wp.settings[k] = params[k];
		      }
		    }
		  } else if (command == 'eraserDown') {
		    wp.drawEraserDown(params, wp);
		  } else if (command == 'eraserUp') {
		    wp.drawEraserUp(null, wp);
		  } else if (command == 'tryEndGame' && APP.rol == 'dibujante') {
		    if (APP.palabra_dibujada == params.palabra_supuesta) {
		      alert('El usuario adivino! Este es el fin del juego.');
		      window.location.replace('limpia.php');
		    }
		  }
		}

		var dispatchCommand = function(command, params) {
		  APP.conn.send(JSON.stringify({session: '<?php echo session_id(); ?>', command: command, params:params}));
		}
		
		var wp = $("#wPaint").wPaint({
		  drawDown: function(e, mode){
		    if (mode == 'Pencil') {
		      /* configuro el color de la 'brocha' */
		      dispatchCommand('settings', {strokeStyle:wp.settings.strokeStyle});
		    }
		    dispatchCommand(mode.toLowerCase() + 'Down', {pageX: e.offsetX, pageY: e.offsetY});
                  
		  },
		  drawMove: function(e, mode) {
		    dispatchCommand('move', {pageX: e.offsetX, pageY: e.offsetY});
		  },
		  drawUp: function(e, mode) {
		    dispatchCommand(mode.toLowerCase() + 'Up', {});
		  }
		}).data('_wPaint');
		
		APP.wp = wp;

		function clearCanvas() {
		  $("#wPaint").wPaint("clear");
		}

		(function() {
		  APP.rol = '<?php echo $_SESSION['rol']; ?>';
                  var conn = new WebSocket('ws://' + document.location.hostname + ':8888/draw');
                  
                  conn.onmessage = function (event) {
                    var message = JSON.parse(event.data);
                    processDispatch(message.command, message.params);
                  };
                  
                  APP.conn = conn;

		  if (APP.rol == 'adivinador') {
		    jQuery('._wPaint_menu.ui-draggable').hide();
                    $(document).ready(function() {
                      $('#palabra_supuesta').keydown(function(event) {
                        if(event.keyCode == 13) {
                          event.preventDefault();
                          APP.tryEndGame();
                          return false;
                        }
                      });
                    });
                  }
                  
		})();
	</script>
	</div>
</body>
</html>